<template>
    <div class="wang-editor" :style="{zIndex}" ref="editor"></div>
</template>

<script>
    import E from 'wangeditor'
    import fileUpload from '../lib/fileUnload'

    export default {
        name: "editor",
        props: {
            value: String,
            zIndex: String,
            height: {
                type: String,
                default: '450px'
            }
        },
        data() {
            return {
                editorContent: '',
                editor: null,
                focus: false
            }
        },
        watch: {
            value(val) {
                this.editor.txt.html(val)
            },
            height(val){
                this.setHeight()
            }
        },
        mounted() {
            this.init()
        },
        methods: {
            // 初始化
            init() {
                this.editor = new E(this.$refs.editor)
                const editor = this.editor
                editor.customConfig.onchange = (html) => {
                    this.editorContent = html
                    this.$emit('input', html)
                }
                editor.customConfig.onfocus = () => {
                    this.$nextTick(() => {
                        this.focus = true
                    })
                }
                editor.customConfig.onblur = () => {
                    this.$nextTick(() => {
                        this.focus = false
                    })
                }
                editor.customConfig.customUploadImg = async (files, insert) => {
                    // files 是 input 中选中的文件列表
                    // insert 是获取图片 url 后，插入到编辑器的方法
                    // 上传代码返回结果之后，将图片插入到编辑器中
                    try {
                        let data = await fileUpload(files[0])
                        insert(data.url)
                    } catch (e) {
                        alert('图片上传失败')
                    }

                }
                editor.create()
                this.setHeight()
                this.editor.txt.html(this.value)
            },
            // 设置高度
            setHeight() {
                this.$refs.editor.getElementsByClassName('w-e-text-container')[0].style.height = this.height
            }
        }
    }
</script>

<style lang="scss">
    .wang-editor {
        position: relative;
        .w-e-toolbar {
            flex-wrap: wrap;
        }
    }
</style>